// 图片上传业务入口类
define([
  "public/business/cropperFz", 
  "public/business/webUploaderFz",
  "public/business/layerFz",
  "text!template/upload-tpl.html!strip"
], function(cropperFz, webUploaderFz, layer, tpl) {
  return function(ops){
    var defaultoOps = {
      defaultPic: "",
      uploadOps: {},
      cropperOps: {},
      type: 1, // 1为需要裁剪，2为需要不需要裁剪
    };

    $.extend(defaultoOps, ops);
  
    function convertImgToBase64(url, callback, outputFormat){
      var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
      img.crossOrigin = 'Anonymous';
      img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL, img.height, img.width);
        canvas = null; 
      };
      img.src = url;
    }

    function getblob(imgSrc, cb, boo) {
      var url = imgSrc;

      convertImgToBase64(url, function(bs64, height, width) {
        var fd = new FormData();
        fd.append('file', bs64);

        cb(fd, height, width);
      });
    }

    function doUpload(formData){
      debugger;
      $.ajax('/agent/index.php?func=upload', {
        method: "POST",
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        success: function(json) {
          defaultoOps.cb && defaultoOps.cb(json.result);
          layer.closeAll();
          layer.msgSuccess();
          console.log('Upload success');
        },
        error: function() {
          layer.msgError();
          $(this).attr("disabled", false);
          console.log('Upload error');
        }
      });
    }

    layer.open({
      type: 1,
      area: ["1000px", "640px"],
      title: false,
      closeBtn: 2,
      shadeClose: false,
      content: $(tpl).html(),
      success: function(){
        var $Image; // 图片

        if (defaultoOps.type == 1) { // 需要裁切（头像）
          $(".previewWapper,.previewDiscribe").css("visibility", "visible");
          if (defaultoOps.defaultPic) { // 有默认头像
            var _html = `<form action="" id="form_upload" method="post" enctype="multipart/form-data">
              <div style="max-width:468px;max-height:396px;overflow:hidden">
                <img src='${defaultoOps.defaultPic}' id='aaa' width="100%"/>
              </div>
            </form>`;

            $("#fileList").append(_html);
            $Image = cropperFz(defaultoOps.cropperOps, $("#aaa"));

            webUploaderFz(defaultoOps.uploadOps, function(img) { // 上传
              $Image = cropperFz(defaultoOps.cropperOps, img); // 裁切
            });
          } else { // 没有默认头像
            webUploaderFz(defaultoOps.uploadOps, function(img) { // 上传
              $Image = cropperFz(defaultoOps.cropperOps, img); // 裁切
            });
          }
        } 
        else if (defaultoOps.type == 2) { // 不需要裁切（证件）
          $(".previewWapper,.previewDiscribe").css("visibility", "hidden");
          if (defaultoOps.defaultPic) { // 有默认证件照

            var _html = `<form action="" id="form_upload" method="post" enctype="multipart/form-data">
              <div style="max-width:468px;max-height:396px;overflow:hidden">
                <img src='${defaultoOps.defaultPic}' id='aaa' width="100%" height="396px"/>
              </div>
            </form>`;

            $("#fileList").append(_html);

            $Image = $("#aaa");
            webUploaderFz(defaultoOps.uploadOps, function(img) { // 上传
              $Image = img;
            });

          } else { // 没有默认证件照
            webUploaderFz(defaultoOps.uploadOps, function(img) { // 上传
              $Image = img;
            });
          }
        }

        // 提交数据
        $(".subbtn button").off("click").on("click", function() {
          if ($Image) {
            var back = $Image.attr("id"); // 回显
            var imgSrc = $Image.attr("src");
          }

          $(this).attr("disabled", true);
          layer.load();

          if (defaultoOps.type == 1) {
            var dataObj = $Image.cropper('getCanvasData');
            var boxObj = $Image.cropper('getCropBoxData');
            var imgObj = $Image.cropper('getImageData');
            getblob(imgSrc, function(formData) {
              formData.append("img_type", 1);
              formData.append("image[width]", parseInt(imgObj.width));
              formData.append("image[height]", parseInt(imgObj.height));
              formData.append("image[x]", parseInt(boxObj.left) - parseInt(dataObj.left));
              formData.append("image[y]", parseInt(boxObj.top) - parseInt(dataObj.top));
              formData.append("cut_width", parseInt(boxObj.width));
              formData.append("cut_height", parseInt(boxObj.height));
              doUpload(formData);
            });
          } else if (defaultoOps.type == 2) {
            debugger;
            getblob(imgSrc, function(formData, height, width) {
              formData.append("img_type", 1);
              formData.append("image[width]", parseInt(width));
              formData.append("image[height]", parseInt(height));
              formData.append("image[x]", 0);
              formData.append("image[y]", 0);
              formData.append("cut_width", parseInt(width));
              formData.append("cut_height", parseInt(height));
              doUpload(formData);
            });
          }

          
        });
      }
    });
    // layer($(tpl).html(), uploadFn);
  };
});